<?php
/**
 * Created by PhpStorm.
 * User: jinqiang
 * Date: 2019/2/4
 * Time: 11:52
 */

namespace App\Http\Services\System;

use App\Http\Models\Mysql\NnyyRolePermission;
use App\Http\Models\Mysql\NnyyRoleTable;
use App\Http\Models\Mysql\NnyyUserTable;
use App\Http\Models\Mysql\OauthAccessTokensTable;
use App\Http\Models\Mysql\SsyFeishuUserJsTable;
use App\Http\Models\Mysql\SsyFeishuUserMzTable;
use App\Http\Models\Mysql\SsyFeishuUserQyxTable;
use App\Http\Models\Mysql\SsyFeishuUserTable;
use App\Http\Models\Mysql\SsyFeishuUserXmTable;
use App\Http\Models\Mysql\SsyFeishuUserYxTable;
use App\Http\Models\Mysql\SsyProcessingFactoryUserTable;

class UserService
{
    //用户来源表
    public static function userTable($subject)
    {
        switch ($subject){
            case 'mz':
                return new SsyFeishuUserMzTable();
            case 'kz':
            case 'qyx':
                return new SsyFeishuUserTable();
            case 'yx':
                return new SsyFeishuUserYxTable();
            case 'xm':
                return new SsyFeishuUserXmTable();
            case 'js':
                return new SsyFeishuUserJsTable();
            default:
                return null;
        }
    }

    public function search($param)
    {
        $conn = (new NnyyUserTable());
        if(!empty($param['name'])){
            $conn = $conn->where('name', 'like', $param['name']."%");
        }
        if(!empty($param['role'])){
            $conn = $conn->where('role', "like", "%".$param['role']."%");
        }
        if(isset($param['status']) && $param['status'] != ""){
            $conn = $conn->where('status', (Int)$param['status']);
        }
        if($param['source_from'] != ""){
            $conn = $conn->where('source_from', $param['source_from']);
        }
        $res = $conn->orderBy('create_time', 'DESC')->paginate((Int)$param['limit'])->toArray();
        $roles = [];
        foreach ($res['data'] as &$item) {
            $item['role'] = !empty($item['role']) ? explode(",", $item['role']) : [];
            $roles = array_merge($roles, $item['role']);
        }
        $roleList = (new NnyyRoleTable())->whereIn('type', $roles)->get(['type', 'label'])->toArray();
        unset($item);
        return [
            'data' => $res['data'],
            'roles' => array_column($roleList, 'label', 'type'),
            'total' => $res['total']
        ];
    }

    public function searchFS($param)
    {
        $subject = $param['subject'];
        $conn = self::userTable($subject);
        if(!empty($param['name'])){
            $conn = $conn->where('name', 'like', $param['name']."%");
        }
        if($param['status'] != ""){
            $conn = $conn->where('status->is_resigned', (Boolean)$param['status']);
        }
        $res = $conn->orderBy('createtime', 'DESC')->paginate((Int)$param['limit'])->toArray();
        foreach ($res['data'] as &$item){
            $item['mobile'] = substr($item['mobile'], 3);
            $item['join_time'] = preg_match("/^[0-9]{9,}$/is", $item['join_time']) ? date("Y-m-d H:i:s", $item['join_time']) : $item['join_time'];
            $item['status'] = json_decode($item['status'], true);
        }
        return [
            'data' => $res['data'],
            'total' => $res['total']
        ];
    }

    public function searchGC($param)
    {
        $conn = new SsyProcessingFactoryUserTable();
        if(!empty($param['name'])){
            $conn = $conn->where('name', 'like', $param['name']."%");
        }
        if($param['status'] != ""){
            $conn = $conn->where('status', (Int)$param['status']);
        }
        if(!empty($param['factory_name'])){
            $conn = $conn->where('factory_name', 'like', "%".$param['factory_name']."%");
        }
        if(!empty($param['supplier_id'])){
            $conn = $conn->where('supplier_id', $param['supplier_id']);
        }
        $res = $conn->orderBy('createtime', 'DESC')->paginate((Int)$param['limit'])->toArray();
        return [
            'data' => $res['data'],
            'total' => $res['total']
        ];
    }

    public function setUser($id, $data)
    {
        try{
            return (new NnyyUserTable())->updateData($id, $data);
        }catch (\Exception $e){
            return ['code' => -1, 'msg' => "操作失败, 请修改内容重新设置"];
        }
    }

    public function setGcUser($id, $data)
    {
        try{
            $res = (new SsyProcessingFactoryUserTable())->updateData($id, $data);
            if($res['code'] === 0){
                $userObj = (new SsyProcessingFactoryUserTable())->where('id', $id)->first(['name', 'phone'])->toArray();
                //状态的修改
                if(isset($data['status'])){
                    $where = ['name' => $userObj['name'], 'phone' => $userObj['phone'], 'source_from' => 'gc'];
                    $exist = (new NnyyUserTable())->where($where)->first();
                    if(empty($exist)){
                       return $res;
                    }
                    //工厂用户状态0启用  1禁用,  和用户列表状态相反 1启用  0禁用
                    return (new NnyyUserTable())->updateData($exist->id, ['status' => $data['status'] == 1 ? 0 : 1]);
                }
            }else{
                return $res;
            }
        }catch (\Exception $e){
            return ['code' => -1, 'msg' => "操作失败, 请修改内容重新设置"];
        }
    }

    public function addUser($param)
    {
        $data = [
            'role' => $param['role'],
            'name' => $param['name'],
            'phone' => $param['phone'],
            'password' => bcrypt($param['phone']),
            'source_from' => $param['source_from'],
            'create_time' => date('Y-m-d H:i:s')
        ];
        $exist = (new NnyyUserTable())->where('name', $data['name'])->where('phone', $data['phone'])->where('source_from', $data['source_from'])->exists();
        if($exist){
            return ['code' => -1, 'msg' => '用户已经存在'];
        }
        return (new NnyyUserTable())->createData($data);
    }

    public function addGcUser($param)
    {
        //是否存在
        $exist = (new SsyProcessingFactoryUserTable())->where(['name' => $param['name'], 'phone' => $param['phone']])->exists();
        if($exist){
            return ['code' => -1, 'msg' => '用户已经存在'];
        }
        $res = (new SsyProcessingFactoryUserTable())->createData([
            'factory_name' => $param['factory_name'],
            'supplier_id' => $param['supplier_id'],
            'name' => $param['name'],
            'phone' => $param['phone'],
            "password" => md5($param['phone']),
            "createtime" => date('Y-m-d H:i:s')
        ]);
        //同步一份到用户列表
        if($res['code'] === 0){
            $exist = (new NnyyUserTable())->where('name', $param['name'])->where('phone', $param['phone'])->where('source_from', 'gc')->exists();
            if(!$exist){
                return (new NnyyUserTable())->createData([
                    'name' => $param['name'],
                    'phone' => $param['phone'],
                    'password' => bcrypt($param['phone']),
                    'source_from' => 'gc',
                    'create_time' => date('Y-m-d H:i:s')
                ]);
            }
            return ['code' => 0, 'msg' => '创建成功'];
        }
        return $res;
    }

    public function getUserInfo($user)
    {
        $subjects = array_column(config('scm.subject'), null, 'is_subject');
        $user['is_subject_label'] = $subjects[$user['is_subject']]['label'] ?? "年年有余";
        $user['discount'] = $subjects[$user['is_subject']]['discount'] ?? 0.68;
        //账号只能使用当前token登录，作废其他token
        //$tokenObj = (new OauthAccessTokensTable())->where('user_id', $user['id'])->orderBy('created_at', 'desc')->first(['created_at'])->toArray();
        //(new OauthAccessTokensTable())->deleteDataWhere(['user_id' => $user['id'], 'created_at' => ['<' => $tokenObj['created_at']]]);
        //工厂用户 获取工厂信息
        if($user['source_from'] == 'gc'){
            $factoryObj = (new SsyProcessingFactoryUserTable())->where(['name' => $user['name'], 'phone' => $user['phone']])->first()->toArray();
            $user['factory_name'] = $factoryObj['factory_name'];
            $user['supplier_id'] = $factoryObj['supplier_id'];
        }
        //获取用户的页面操作权限
        $roleList = (new NnyyRoleTable())->whereIn('type', explode(",", $user['role']))->get(['id'])->toArray();
        if(empty($roleList)){
            return $user;
        }
        $permissionList = (new NnyyRolePermission())->whereIn('role_id', array_column($roleList, 'id'))->get(['node_actions'])->toArray();
        if(empty($permissionList)){
            return $user;
        }
        $nodeActions = [];
        foreach ($permissionList as $item){
            $action = json_decode($item['node_actions'], true);
            foreach ($action as $id => $items){
                if(isset($nodeActions[$id])){
                    $nodes = array_unique(array_merge($nodeActions[$id], $items));
                    sort($nodes);
                    $nodeActions[$id] = $nodes;
                }else{
                    $nodeActions[$id] = $items;
                }
            }
        }
        $user['node_actions'] = $nodeActions;
        return $user;
    }

    public function sync($param)
    {
        $subject = $param['subject'];
        $conn = self::userTable($subject);
        $fsUser = $conn->select(['mobile', 'name', 'user_id', 'open_id', 'union_id'])->where('id', $param['id'])->first()->toArray();
        $phone = substr($fsUser['mobile'], 3);
        $exist = (new NnyyUserTable())->where(['phone' => $phone, 'name' => $fsUser['name'], 'source_from' => 'fs'])->first();
        if(empty($exist)){
            $data = [
                'name' => $fsUser['name'],
                'phone' => $phone,
                'password' => bcrypt($phone),
                'create_time' => date('Y-m-d H:i:s'),
                "{$subject}_feishu_user_id" => $fsUser['user_id'],
                "{$subject}_feishu_union_id" => $fsUser['union_id'],
                "{$subject}_feishu_open_id" => $fsUser['open_id'],
                'source_from' => 'fs'
            ];
            return (new NnyyUserTable())->createData($data);
        }else{
            $data = [
                "{$subject}_feishu_user_id" => $fsUser['user_id'],
                "{$subject}_feishu_union_id" => $fsUser['union_id'],
                "{$subject}_feishu_open_id" => $fsUser['open_id'],
            ];
            return (new NnyyUserTable())->updateData($exist->id, $data);
        }
    }

    public function changeSubject($subject)
    {
        $user = auth()->guard("api")->user()->toArray();
        $conn = self::userTable($subject);
        $userId = in_array($subject, ['kz', 'qyx']) ? $user["kz_feishu_user_id"] : $user[$subject."_feishu_user_id"];
        $fsUser = $conn->where('user_id', $userId)->where('name', $user['name'])->first();
        if(empty($fsUser)){
            return ['code' => -1, 'msg' => '切换的飞书用户不存在: '.$subject];
        }
        $status = json_decode($fsUser->status, true);
        if($status['is_resigned']){
            return ['code' => -1, 'msg' => '切换的飞书用户已离职: '.$subject];
        }
        return (new NnyyUserTable())->updateData($user['id'], ['is_subject' => $subject]);
    }

    public function resetPassword($param)
    {
        $user = (new NnyyUserTable())->where('name', $param['name'])->first(['password'])->toArray();
        if(!password_verify($param['password_old'], $user['password'])){
            return ['code' => -1, 'msg' => '提示：旧密码填写错误'];
        }
        $data = ['password' => bcrypt($param['password'])];
        return (new NnyyUserTable())->updateData($param['name'], $data);
    }

    public function updatePassword($param)
    {
        $data = ['password' => bcrypt($param['password'])];
        return (new NnyyUserTable())->updateDataByPhone($param['phone'], $data);
    }
}
